/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedInstanceException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;
import ar.uba.fi.posgrado.economy.dao.CustomerAccountDAO;
import ar.uba.fi.posgrado.economy.exception.AccountRuleException;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.CustomerAccount;
import ar.uba.fi.posgrado.economy.service.CustomerAccountService;

/**
 * Servicio concreto para cuentas corrientes de clientes.<br>
 * 
 * @author nicolas.gonzalez
 * @see CustomerAccountService
 */
public class CustomerAccountServiceImpl implements CustomerAccountService {

	/** Logger */
	private static Logger logger = Logger
			.getLogger(CustomerAccountServiceImpl.class);

	private CustomerAccountDAO customerAccountDAO;

	/**
	 * 
	 * @return el dao de cuentas corrientes
	 */
	public CustomerAccountDAO getCustomerAccountDAO() {
		return this.customerAccountDAO;
	}

	/**
	 * 
	 * @param customerAccountDAO
	 */
	public void setCustomerAccountDAO(CustomerAccountDAO customerAccountDAO) {
		this.customerAccountDAO = customerAccountDAO;
	}

	public CustomerAccountServiceImpl() {

	}

	/**
	 * Constructor para prueba unitaria
	 * 
	 * @param customerAccountDAO
	 */
	public CustomerAccountServiceImpl(CustomerAccountDAO customerAccountDAO) {
		this.setCustomerAccountDAO(customerAccountDAO);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(CustomerAccount customerAccount)
			throws PosgradoRuntimeException, PosgradoException,
			RepeatedInstanceException, AccountRuleException {
		if (((customerAccount.getInFavorCredit().compareTo(new Double(0)) != 0) && (customerAccount
				.getTotalDebt().compareTo(new Double(0)) != 0))) {
			throw new AccountRuleException(
					"No se pueden crear Cuentas Corrientes con saldo positivo, ni con deudas");
		}
		try {
			this.getCustomerAccountDAO().save(customerAccount);
			logger.info("Cuenta Corriente del cliente: "
					+ customerAccount.getCustomer().getName()
					+ " creada con exito");
		} catch (DAOException e) {
			throw new PosgradoException(
					"Excepcion al crear la cuenta corriente del cliente: "
							+ customerAccount.getCustomer().getName(), e);
		}
	}

	public CustomerAccount getByCustomerId(Long customerId)
			throws PosgradoRuntimeException, PosgradoException {
		return this.getCustomerAccountDAO().findByCustomerId(customerId);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public CustomerAccount update(CustomerAccount customerAccount)
			throws PosgradoRuntimeException, PosgradoException,
			NoSuchEntityException, RepeatedNameException {

		if (customerAccount.getInFavorCredit().compareTo(new Double(0)) > 0
				&& customerAccount.getTotalDebt().compareTo(new Double(0)) > 0) {
			String mensaje = "No se pueden crear Cuentas Corrientes con saldo positivo, ni con deudas";
			AccountRuleException e = new AccountRuleException(mensaje);
			throw e;
		}
		CustomerAccount toUpdateAccount = this.getById(customerAccount.getId());

		toUpdateAccount.setInFavorCredit(customerAccount.getInFavorCredit());
		toUpdateAccount.setTotalDebt(customerAccount.getTotalDebt());

		customerAccount = this.update(toUpdateAccount);
		return customerAccount;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(CustomerAccount customerAccount)
			throws PosgradoRuntimeException, PosgradoException {
		try {
			CustomerAccount customerAccountToDelete = this
					.getById(customerAccount.getId());
			this.getCustomerAccountDAO().remove(customerAccountToDelete);
		} catch (NoSuchEntityException e) {
			throw new PosgradoException(
					"Error al borrar cta cte. No se encontro ninguna cuenta con id '"
							+ customerAccount.getId() + "' en el sistema", e);
		}
	}

	public List<CustomerAccount> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		List<CustomerAccount> customerAccounts = null;
		try {
			customerAccounts = this.getCustomerAccountDAO().findAll();
		} catch (DAOException e) {
			throw new PosgradoException(
					"Ocurrio un error al obtener todas las ctas ctes", e);
		}
		return customerAccounts;
	}

	public CustomerAccount getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		CustomerAccount customerAccount = null;
		try {
			customerAccount = (CustomerAccount) this.getCustomerAccountDAO()
					.findById(id);
		} catch (DAOException e) {
			throw new PosgradoException("Ocurrio un error al obtener "
					+ "la cuenta con Id " + id, e);
		}
		return customerAccount;
	}

	public Customer getCustomerByAccountId(Long accountId)
			throws PosgradoRuntimeException, PosgradoException {
		Customer customer = null;
		try {
			CustomerAccount account = this.getById(accountId);
			customer = account.getCustomer();
		} catch (DAOException e) {
			throw new PosgradoException("Ocurrio un error al obtener "
					+ "el cliente de la cuenta con Id " + accountId, e);
		}
		return customer;
	}

	/** 
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List, ar.uba.fi.posgrado.common.model.User)
	 */
	public List<CustomerAccount> filter(List<CustomerAccount> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		return list;
	}

}
